# -*- coding: UTF-8 -*-
"""
@author:zhangxing
@file:selenium_middlewares.py
@time:2021/03/15
"""
import os
import sys
import time

from selenium import webdriver
from selenium.webdriver import ActionChains
from selenium.webdriver.support.wait import WebDriverWait

"""
            

    ActionChains:ActionChains的执行原理，当你调用ActionChains的方法时，不会立即执行，而是会将所有的操作按顺序存放在一个队列里，
    当调用perform()方法时，队列中的事件会依次执行
    first_page_url:
    iframe:False
    click_button_xpath:
    next_page_button_xpath:下一页xpath
    click_times =None
    if not click_times:
        通过source_page是否变化来判断
"""

class SeleniumUtils:
    """
    action_lists:
    要求：
        1)整体是一个list
        2)内部的每个元素也是一个list
        3)list中的每个元素格式
            [0] get_element  [1]
    """

    def __init__(self,  action_lists, url=None,headless=True):
        options = webdriver.ChromeOptions()
        if headless:
            options.add_argument('--headless')
        if sys.platform.startswith('win'):
            print("===", os.path.dirname(os.path.abspath(__file__)))
            chromedriver_path = os.path.join(os.path.dirname(os.path.abspath(__file__)),
                                             "../../inner_utils/driver/chromedriver.exe")
        else:
            chromedriver_path = os.path.join(os.path.dirname(os.path.abspath(__file__)),
                                             "../../inner_utils/driver/chromedriver")
        self.action_lists = action_lists
        self.driver = webdriver.Chrome(options=options, executable_path=chromedriver_path)
        if url:
            self.driver.get(url=url)
            self.driver.implicitly_wait(2)


    def parse_action(self):
        # element_find = self.driver.find_element_by_id("kw")
        ac = ActionChains(self.driver)
        for action_list in self.action_lists:
            if action_list[0] == "next_page":
                return self.handle_next_page()

    def handle_next_page(self, next_page_button_xpath):
        click_element = self.driver.find_element_by_xpath('//ul[@class="m-pagination-page"]/li[last()-1]')
        click_element.click()
        WebDriverWait.until()
        time.sleep(2)
        return self.driver.page_source

    def close(self):
        self.driver.close()
        self.driver.quit()


if __name__ == '__main__':
    action_lists = [
        ["next_page"],
        []
    ]
    # url = "https://www.baidu.com/s?wd=%E4%BC%97%E8%83%BD"
    url = "http://jsggzy.jszwfw.gov.cn/jyxx/tradeInfonew.html"
    s = SeleniumUtils(url, action_lists, headless=False)
    s.parse_action()
    s.close()
